import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { convertMenusToRoutes } from '@/utils/menu-utils'
const constantRoutes = [

      {
        path: '/',
        name: 'login',
        component: () => import('@/views/login/index.vue')
      }
]
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: constantRoutes // 初始只有固定路由
})
/**
 * 登录校验（全局路由守卫）
 */
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  const token = userStore.token
  const whiteList = ['/']

  if (!token && !whiteList.includes(to.path)) {
    return next('/')
  }

  if (!userStore.dynamicRoutesAdded) {
    const asyncRoutes = convertMenusToRoutes(userStore.userInfo.menus || [])
    asyncRoutes.forEach(route => router.addRoute(route))
    userStore.dynamicRoutesAdded = true

    return next(to.fullPath)
  }

  next()
})

export default router
